/** 
 * 程序入口，拥有以下职责：
 * 1. 加载必要的通用组件或样式
 * 2. 配置顶层路由
 * 3. 配置frontend-commons
 * 4. 初始化Message和Dialog组件
 */

import React, { useEffect, useState } from 'react';
import dayjs from 'dayjs';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { useStore } from '@shared/store';
import customService from './services/overrides';
import { dynamic } from "@shared/components/DynamicComponent";
import Message, { initialize as initializeMessage } from '@shared/components/Message';
import { initialize as initializeDialog } from '@shared/components/Dialog';
initializeMessage(() => import(/* webpackChunkName: "AdminMessage" */'./components/AdminMessage'));
initializeDialog(() => import(/* webpackChunkName: "AdminDialog" */'./components/AdminDialog'));

import { config as configLib } from '@ugeez/frontend-commons';
import { setting } from '@shared/config';
import { IAdminStore } from '@shared/types';
import { Login, Main } from './pages';

import { initialize as initializeLocale } from './lang';
import { LocaleProvider } from '@douyinfe/semi-ui';

import './store';

configLib(customService({
    moment: dayjs,
    getToken: (): string => {
        const store = useStore<IAdminStore>();
        return store.user.auth || '';
    },
    setting: {
        ...setting
    },
    errorHandlers: {
        authFail: (err) => {
            useStore<IAdminStore>().logout();
            window.location.href = '/login';
            return true;
        },
        apiFail: (err) => {
            Message.error(`${err.message}`);
        }
    },
    service: {}
}));

export default () => {

    const [locale, setLocale] = useState();

    useEffect(() => {
        const store = useStore<IAdminStore>();
        
        import(/* webpackChunkName: "styles" */'./styles');
        initializeLocale(store.locale).then(({ frameworkLocaleModule }) => {
            setLocale(frameworkLocaleModule);
        });
    }, []);

    return <LocaleProvider locale={locale}>
        <Router>
            <Switch>
                <Route path="/login" component={dynamic(Login)} />
                <Route path="/" component={dynamic(Main)} />
            </Switch>
        </Router>
    </LocaleProvider>;
};
